package com.link.base.base.consumer.service;

import com.link.base.base.user.service.UserService;
import com.link.base.core.basic.interceptors.mybatis.system.KafkaSender;
import com.link.base.user.model.CoreUser;
import com.link.base.base.user.model.User;
import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.dao.mybatis.mapper.AcctAddressMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.model.AcctAddress;
import com.link.base.base.consumer.dao.mybatis.mapper.ImpData2AccntMapper;
import com.link.base.base.consumer.dao.mybatis.mapper.prodMapMapper;
import com.link.base.base.consumer.exception.RepeatOrderNoException;
import com.link.base.base.consumer.model.ImpOrder;
import com.link.base.base.consumer.model.ProdConvert;
import com.link.base.base.consumer.util.poi.PoiUtil;
import com.link.base.base.order.dao.mybatis.mapper.SaleOrderItemMapper;
import com.link.base.base.order.dao.mybatis.mapper.SaleOrderMapper;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.model.SaleOrderItem;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.modules.export.FileIndexGenarate;
import com.link.core.util.AppConstants;
import com.link.core.util.JsonUtil;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 20180425
 *
 * @author Li Yang
 * 此类为个性化导入订单生成相关消费者（客户），订单及地址等信息。
 * 此类及类中的方法目前为定制方法，暂不具备通用性
 */
@Service
public class ImpData2AccountServiceImpl extends BasicServiceImpl<ImpOrder> implements ImpData2AccntService {


    @Resource
    private ImpData2AccntMapper impData2AccntMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private prodMapMapper prodMapMapper;

    @Resource
    private AccountMapper accountMapper;

    @Resource
    private PortalAccntLineTemporaryService portalAccntLineTemporaryService;

    @Resource
    private SaleOrderMapper saleOrderMapper;

    @Resource
    private SaleOrderItemMapper saleOrderItemMapper;

    @Resource
    private AcctAddressMapper acctAddressMapper;

    @Resource
    private UserService userService;
    /**
     * 导出文件生成路径
     */
    private String excelFilePath;
    /**
     * 生成excel下载路径
     */
    private String excelUrlPath;

    @Override
    public BasicMapper<ImpOrder> getBasicMapper() throws Exception {
        return impData2AccntMapper;
    }

    /**
     * 导入订单头
     *
     * @throws Exception
     */
    @Override
    public String generateAccntFromOrder(String orderSouce, QueryParams qps, HttpServletRequest request) throws Exception, RepeatOrderNoException {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile myfile = multipartRequest.getFile("importFile");
        CommonsMultipartFile cf = (CommonsMultipartFile) myfile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        String fileName = myfile.getOriginalFilename();
        String sufix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        sufix = sufix.toLowerCase();
        String xlsSufix = ".xls";
        String xlsxSufix = ".xlsx";
        if (xlsSufix.equals(sufix) || xlsxSufix.equals(sufix)) {
            processExcelData(file, AppConstants.APP_EXPORT_ENCODING, orderSouce);
        }

        return null;
    }

    /**
     * 处理导入的excel文件
     *
     * @param file
     * @param encoding
     * @param orderSource
     * @return
     * @throws Exception
     */
    public Map<String, String> processExcelData(File file, String encoding, String orderSource) throws Exception, RepeatOrderNoException {

        //定义标题行与model中字段的映射关系
        Map<String, Object> titleMap = new HashMap<String, Object>(64);
        titleMap.put("序号", "seq");
        titleMap.put("商铺名称", "shopName");
        titleMap.put("订单号", "orderCode");
        titleMap.put("下单日期", "orderDate");
        titleMap.put("买家Id", "buyerId");
        titleMap.put("买家备注", "buyerComments");
        titleMap.put("卖家备注", "sellerComments");
        titleMap.put("快递公司", "logisticsCompany");
        titleMap.put("快递单号", "logisticsNo");
        titleMap.put("总金额", "summaryAmount");
        titleMap.put("实付", "orderTotalAmount");
        titleMap.put("运费", "freight");
        titleMap.put("付款时间", "payTime");
        titleMap.put("商品SKU", "sku");
        titleMap.put("规格", "prodStandard");
        titleMap.put("零售价", "prodPrice");
        titleMap.put("数量", "prodNum");
        titleMap.put("优惠", "discount");
        titleMap.put("应付", "actualPayment");
        titleMap.put("收货人姓名", "recieverName");
        titleMap.put("收货人手机号", "recieverPhone");
        titleMap.put("收货人固定电话", "recieverTel");
        titleMap.put("邮编", "zipCode");
        titleMap.put("省", "province");
        titleMap.put("市", "city");
        titleMap.put("区/县", "district");
        titleMap.put("详细地址", "address");
        titleMap.put("备注", "comments");

        generateImpOrderList(titleMap, file, orderSource);
        Map<String, String> result = new HashMap<String, String>(2);
        return result;
    }

    private List<ImpOrder> generateImpOrderList(Map<String, Object> titleMap, File file, String orderSource)
            throws Exception, RepeatOrderNoException {

        //开始处理导入的数据
        XSSFWorkbook xssfWorkbook = null;
        try {
            //初始化处理输入的excel的相关工具类
            InputStream is = new FileInputStream(file);
            xssfWorkbook = new XSSFWorkbook(is);
            //初始化处理输出处理失败的相关工具类
//          File outFile = new File(this.excelFilePath);
        } catch (FileNotFoundException e) {
            LCLogger.error().withMessageKey("generateImpOrderList")
                    .withMessage("读取导入订单文件异常。").flush();
            LCLogger.withException(e);
        } catch (IOException e) {
            LCLogger.error().withMessageKey("generateImpOrderList")
                    .withMessage("创建导入文件的工作簿异常。").flush();
            LCLogger.withException(e);
        }
        //初始化客户以及订单对象
        CoreUser user = UserUtil.getUser();
        Long userId = user.getId();
        Long corpId = user.getCorpid();
        System.out.println(userId + " : " + corpId);
        //开始处理excel
        if (null != xssfWorkbook) {
            //循环页签
            for (int sheetNum = 0; sheetNum < xssfWorkbook.getNumberOfSheets(); sheetNum++) {
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(sheetNum);
                //如果页签为空，则跳过该页签
                if (null != xssfSheet) {
                    LCLogger.info().withMessageKey("generateImpOrderList")
                            .withMessage("创建导入对象...").flush();
                    List<ImpOrder> impOrderList = PoiUtil.getBeanFromExcelRow(ImpOrder.class, xssfSheet, titleMap);
                    for (int i = 0; i < impOrderList.size(); i++) {
                        ImpOrder impOrder = impOrderList.get(i);
                        //设置订单来源渠道
                        impOrder.setOrderSource(orderSource);
//                      try {
                        //查询是否包含此订单头
                        ImpOrder existImpOrder = impData2AccntMapper.queryTempOrderByOrderNum(impOrder);
                        //如果没有，则新建，如果有，则更新
                        if (null == existImpOrder) {
                            //导入订单头临时表
                            Long id = keyGenerateDao.keyGenerate();
                            impOrder.setId(id);
                            impOrder.setHeadId(id);
                            impOrder.setCreatedBy(userId);
                            impOrder.setLastUpdatedBy(userId);
                            impOrder.setCorpid(corpId);
                            impOrder.setCheckStatus("New");
                            impData2AccntMapper.tempOrderHeadInsert(impOrder);
                            //导入订单行临时表
                            id = keyGenerateDao.keyGenerate();
                            impOrder.setId(id);
                            impData2AccntMapper.tempOrderItemInsert(impOrder);
                        } else {
                            if (!existImpOrder.getOrderSource().equals(impOrder.getOrderSource())) {
                                throw new RepeatOrderNoException("其它渠道待导入订单存在与单号为：" + impOrder.getOrderCode() + "相同的订单，上传终止！");
                            } else {
                                //导入订单行临时表
                                impOrder.setHeadId(existImpOrder.getId());
                                Long id = keyGenerateDao.keyGenerate();
                                impOrder.setId(id);
                                impOrder.setCreatedBy(userId);
                                impOrder.setLastUpdatedBy(userId);
                                impOrder.setCorpid(corpId);
                                impData2AccntMapper.tempOrderItemInsert(impOrder);
                            }
                        }
                    }
                }
            }
        }

        List<ImpOrder> result = new ArrayList<ImpOrder>();
        return result;
    }

    /**
     * 初始化导出文件的路径
     */
    private void initPath() {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat datetimeFormatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        Random random = new Random();
        String relatePath = "/export/" + dateFormatter.format(new Date()) + "/" + datetimeFormatter.format(new Date())
                + "_" + FileIndexGenarate.getFileIndex(new Date()) + "_" + random.nextInt(100) + "/";
        File file = new File(YmlConstants.getTemporaryIOFileDir() + relatePath);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("file: '" + YmlConstants.getTemporaryIOFileDir() + relatePath + "' is not exists!");
            file.mkdirs();
        }
        String tempzipfile = random.nextInt(100) + ".xlsx";
        this.excelFilePath = YmlConstants.getTemporaryIOFileDir() + "/" + relatePath + "_" + tempzipfile;
        this.excelUrlPath = YmlConstants.getTemporaryIOUrlDir() + "/" + relatePath + "_" + tempzipfile;
    }

    @Override
    public List<ImpOrder> queryImportOrderHeadPage(ImpOrder record) throws Exception {
        List<ImpOrder> result = impData2AccntMapper.queryImportOrderHeadPage(record);
        return result;
    }

    @Override
    public List<ImpOrder> queryImportOrderItemPage(ImpOrder record) throws Exception {
        List<ImpOrder> result = impData2AccntMapper.queryImportOrderItemPage(record);
        return result;
    }

    @Override
    public void deleteTempOrder(ImpOrder record) throws Exception {
        impData2AccntMapper.deleteTempOrder(record);
    }

    @Override
    public void deleteTempOrderItem(ImpOrder record) throws Exception {
        impData2AccntMapper.deleteTempOrderItem(record);
    }

    @Override
    public void tempOrderHeadUpdate(ImpOrder record) throws Exception {
        impData2AccntMapper.tempOrderHeadUpdate(record);
    }

    @Override
    public void tempOrderItemUpdate(ImpOrder record) throws Exception {
        impData2AccntMapper.tempOrderItemUpdate(record);
    }

    @Override
    public void checkOrder() throws Exception {
        CoreUser user = UserUtil.getUser();
        if (null == user) {
            user = new User();
            user.setId(0L);
        }
        ImpOrder queryImpOrder = new ImpOrder();
        queryImpOrder.setCreatedBy(user.getId());
        queryImpOrder.setPageFlag(false);
        //查询新增的订单
        queryImpOrder.setCheckStatus("New");
        List<ImpOrder> impOrderList = impData2AccntMapper.queryImportOrderHeadPage(queryImpOrder);
        for (int i = 0; i < impOrderList.size(); i++) {
            ImpOrder impOrderHead = impOrderList.get(i);
            //查询头下的所有订单行
            impOrderHead.setPageFlag(false);
            impOrderHead.setHeadId(impOrderHead.getId());
            List<ImpOrder> impOrderItemList = impData2AccntMapper.queryImportOrderItemPage(impOrderHead);
            Map<String, String> checkResult = checkImpOrder(impOrderHead, impOrderItemList);
            if ("true".equals(checkResult.get("success"))) {
                //校验成功，修改记录的校验状态为成功
                impOrderHead.setCheckStatus("Success");
                impOrderHead.setMessage(null);
                impData2AccntMapper.tempOrderStatusUpdate(impOrderHead);
            } else {
                //校验失败，修改记录的校验状态为失败并回写失败信息
                String errMsg = checkResult.get("errMsg");
                impOrderHead.setMessage(errMsg);
                impOrderHead.setCheckStatus("Failure");
                impData2AccntMapper.tempOrderStatusUpdate(impOrderHead);
            }
        }
        //查询校验失败的订单
        queryImpOrder.setCheckStatus("Failure");
        List<ImpOrder> impOrderListFail = impData2AccntMapper.queryImportOrderHeadPage(queryImpOrder);
        for (int i = 0; i < impOrderListFail.size(); i++) {
            ImpOrder impOrderHead = impOrderListFail.get(i);
            //查询头下的所有订单行
            impOrderHead.setPageFlag(false);
            impOrderHead.setHeadId(impOrderHead.getId());
            List<ImpOrder> impOrderItemList = impData2AccntMapper.queryImportOrderItemPage(impOrderHead);
            Map<String, String> checkResult = checkImpOrder(impOrderHead, impOrderItemList);
            if ("true".equals(checkResult.get("success"))) {
                //校验成功，修改记录的校验状态为成功
                impOrderHead.setCheckStatus("Success");
                impOrderHead.setMessage(null);
                impData2AccntMapper.tempOrderStatusUpdate(impOrderHead);
            } else {
                //校验失败，修改记录的校验状态为失败并回写失败信息
                String errMsg = checkResult.get("errMsg");
                impOrderHead.setMessage(errMsg);
                impOrderHead.setCheckStatus("Failure");
                impData2AccntMapper.tempOrderStatusUpdate(impOrderHead);
            }

        }

    }

    /**
     * 导入的电商订单具体的校验方法
     *
     * @param orderHead
     * @param orderItemList
     * @return
     */
    private Map<String, String> checkImpOrder(ImpOrder orderHead, List<ImpOrder> orderItemList) {
        Map<String, String> result = new HashMap<String, String>(2);
        StringBuilder errMsg = new StringBuilder("");
        //0.先判断系统是否包含该订单
        SaleOrder saleOrderParam = new SaleOrder();
        saleOrderParam.setOrderNo(orderHead.getOrderCode());
        saleOrderParam.setPageFlag(false);
        List<SaleOrder> saleOrderListResult = new ArrayList<SaleOrder>();
        try {
            saleOrderListResult = saleOrderMapper.queryByExamplePage(saleOrderParam);
        } catch (Exception e1) {
            errMsg.append("校验订单是否已存在系统中出现异常；");
            LCLogger.withException(e1);
        }
        //如果系统已有该订单，则不进行下面的校验，如果没有再进行下面的校验
        System.out.println(saleOrderListResult.size());
        if (0 < saleOrderListResult.size()) {
            errMsg.append("该订单号已存在，不能重复导入；");
        } else {
            //订单行-应付汇总
            Double summaryOrderItemPay = new Double(0);
            for (int i = 0; i < orderItemList.size(); i++) {
                ImpOrder orderItem = orderItemList.get(i);
                try {
                    //获取订单行应付汇总
                    summaryOrderItemPay = summaryOrderItemPay + Double.parseDouble(orderItem.getActualPayment());
                } catch (Exception e) {
                    LCLogger.withException(e);
                    errMsg.append("订单行应付金额格式异常；");
                }
                //6.校验商品sku
                ProdConvert sku = new ProdConvert();
                sku.setPageFlag(false);
                sku.setSku(orderItem.getSku());
                try {
                    List<ProdConvert> skuList = prodMapMapper.queryByExamplePage(sku);
                    if (skuList.size() == 0) {
                        errMsg.append("订单行sku为:" + sku.getSku() + "的商品未在系统中维护；");
                    }
                    if (skuList.size() > 1) {
                        errMsg.append("订单行sku为:" + sku.getSku() + "的商品在系统中维护了多条；");
                    }
                    if (skuList.size() == 1) {
                        //将对应的产品id写入临时表
                        orderItem.setProdId(skuList.get(0).getProdId());
                        impData2AccntMapper.tempOrderItemUpdate(orderItem);
                    }
                } catch (Exception e) {
                    LCLogger.withException(e);
                    errMsg.append("查询系统产品与sku映射关系出现异常；");
                }

                //7.校验订单行优惠是否符合条件
                try {
                    Double discount = Double.parseDouble(orderItem.getDiscount());
                    //这里未做行上金额、优惠与头金额的校验
                } catch (Exception e) {
                    LCLogger.withException(e);
                    errMsg.append("订单行优惠金额格式异常；");
                }

                //9.校验数量格式是否符合要求
                try {
                    Double.parseDouble(orderItem.getProdNum());
                } catch (Exception e) {
                    LCLogger.withException(e);
                    errMsg.append("订单行数量格式异常；");
                }
            }

            //1.校验订单行是否正确（1.头的总金额与行的应付是否相等）
            Double summaryAmount = new Double(0);
            try {
                summaryAmount = Double.parseDouble(orderHead.getSummaryAmount());
                if (summaryAmount.compareTo(summaryOrderItemPay) != 0) {
                    errMsg.append("订单行金额与订单头总金额不符；");
                }
            } catch (Exception e) {
                LCLogger.withException(e);
                errMsg.append("订单头总金额格式异常；");
            }

            //2.校验实付是否等于总金额+运费
            try {
                Double orderTotalAmount = Double.parseDouble(orderHead.getOrderTotalAmount());
                Double freight = Double.parseDouble(orderHead.getFreight());
                if (orderTotalAmount.compareTo(freight + summaryAmount) != 0) {
                    errMsg.append("实付金额不等于订单总金额+运费；");
                }
            } catch (Exception e) {
                LCLogger.withException(e);
                errMsg.append("订单头实付或运费金额格式异常；");
            }

            //3.校验时间字段是否符合日期格式
            if (!PoiUtil.valiDateTimeWithLongFormat(orderHead.getOrderDate())) {
                errMsg.append("下单时间格式有误，请参照如下格式填写 2017-01-12 12:32:56；");
            }
            if (!PoiUtil.valiDateTimeWithLongFormat(orderHead.getPayTime())) {
                errMsg.append("付款时间格式有误，请参照如下格式填写 2017-01-12 12:32:56；");
            }
            //4.校验地址的省市县是否符合要求
            Map<String, Object> addrCheckMap = portalAccntLineTemporaryService
                    .queryAddrCheck(orderHead.getProvince(), orderHead.getCity(), orderHead.getDistrict());
            boolean addrCheckFlag = (boolean) addrCheckMap.get("success");
            if (!addrCheckFlag) {
                errMsg.append((String) addrCheckMap.get("msg"));
            }

            //5.校验手机号
            if (!PoiUtil.valiPhoneNumFormat(orderHead.getRecieverPhone())) {
                errMsg.append("收货人手机号不符合要求；");
            }

            //8.收货人姓名不能为空
            if (StringUtils.isBlank(orderHead.getRecieverName())) {
                errMsg.append("收货人不能为空；");
            }

            //10.校验导入文件商铺是否已在系统中维护
            Account accntParam = new Account();
            accntParam.setAcctType("E-Commerce");
            accntParam.setAcctChannel(orderHead.getOrderSource());
            String shopName = orderHead.getShopName().trim();
            if (StringUtils.isBlank(shopName)) {
                errMsg.append("店铺名称不允许为空；");
            } else {
                accntParam.setAcctName(shopName);
                accntParam.setPageFlag(false);
                try {
                    List<Account> accntList = accountMapper.queryByExamplePage(accntParam);
                    if (null == accntList || accntList.size() == 0 || accntList.size() > 1) {
                        errMsg.append("系统中未维护该商铺或维护了多条该商铺记录；");
                    }
                } catch (Exception e) {
                    LCLogger.withException(e);
                    errMsg.append("查询商铺出现异常；");
                }
            }
        }
        //返回校验结果
        if (StringUtils.isBlank(errMsg.toString())) {
            result.put("success", "true");
        } else {
            result.put("success", "false");
            result.put("errMsg", errMsg.toString());
        }
        return result;
    }

    @Override
    public void cancelImport(ImpOrder record) throws Exception {
        impData2AccntMapper.cancelImport(record);
    }

    @Override
    public void generateConsumer() throws Exception {
        //初始化查询信息
        CoreUser user = UserUtil.getUser();
        if (null == user) {
            user = new CoreUser();
            user.setId(0L);
        }
        ImpOrder queryImpOrder = new ImpOrder();
        //查询当前登录人创建的记录
        queryImpOrder.setCreatedBy(user.getId());
        queryImpOrder.setPageFlag(false);
        //查询校验状态为成功的记录
        queryImpOrder.setCheckStatus("Success");
        //需要导入的记录的结果集
        List<ImpOrder> needImpOrderList = impData2AccntMapper.queryImportOrderHeadPage(queryImpOrder);
        for (int i = 0; i < needImpOrderList.size(); i++) {
            //回写的异常信息
            String errMsg = "";
            ImpOrder impOrderHead = needImpOrderList.get(i);
            //1.生成消费者
            //判断是否包含该消费者
            Account queryAccnt = new Account();
            queryAccnt.setMobilePhone1(impOrderHead.getRecieverPhone());
            queryAccnt.setAcctType("ChannelConsumer");
            queryAccnt.setAcctChannel(impOrderHead.getOrderSource());
            queryAccnt.setPageFlag(false);
            List<Account> accntList = accountMapper.queryByExamplePage(queryAccnt);
            //如果没有该消费者记录则创建消费者↓
            try {
                if (accntList.size() == 0) {
                    //1.生成消费者
                    Account accnt = generateAccount(impOrderHead, user);
                    accountMapper.insert(accnt);
                    // dmp同步
                    //accnt.setDataSource2("Link");
                    Object object = userService.transformToDmpConsumer(accnt);
                    KafkaSender.sendInfo("CDC_CONSUMER", JsonUtil.toString(object));
                    //2.生成订单头
                    SaleOrder saleOrder = generateOrder(impOrderHead, user, accnt.getId());
                    saleOrderMapper.insert(saleOrder);

                    //查询头下的所有订单行
                    impOrderHead.setPageFlag(false);
                    impOrderHead.setHeadId(impOrderHead.getId());
                    List<ImpOrder> impOrderItemList = impData2AccntMapper.queryImportOrderItemPage(impOrderHead);
                    //3.生成订单行及相关连的产品
                    for (int j = 0; j < impOrderItemList.size(); j++) {
                        ImpOrder impOrderItem = impOrderItemList.get(j);
                        SaleOrderItem saleOrderItem = generateOrderItem(impOrderItem, user);
                        //添加头id
                        saleOrderItem.setHeadId(saleOrder.getId());
                        saleOrderItemMapper.insert(saleOrderItem);
                    }
                    //4.生成客户地址
                    AcctAddress addr = generateAcctAddress(impOrderHead, user, accnt.getId());
                    acctAddressMapper.insert(addr);
                } else {
                    //如果已有消费者，则直接添加该消费者的订单
                    //          //生成订单头
                    SaleOrder saleOrder = generateOrder(impOrderHead, user, accntList.get(0).getId());
                    saleOrderMapper.insert(saleOrder);

                    //查询头下的所有订单行
                    impOrderHead.setPageFlag(false);
                    impOrderHead.setHeadId(impOrderHead.getId());
                    List<ImpOrder> impOrderItemList = impData2AccntMapper.queryImportOrderItemPage(impOrderHead);
                    //生成订单行及相关连的产品
                    for (int j = 0; j < impOrderItemList.size(); j++) {
                        ImpOrder impOrderItem = impOrderItemList.get(j);
                        SaleOrderItem saleOrderItem = generateOrderItem(impOrderItem, user);
                        //添加头id
                        saleOrderItem.setHeadId(saleOrder.getId());
                        saleOrderItemMapper.insert(saleOrderItem);
                    }
                }
            } catch (Exception e) {
                LCLogger.withException(e);
                errMsg = errMsg + "订单号为：" + impOrderHead.getOrderCode() + " 的订单生成消费者时出现异常；";
            }
            //判断是否成功生成所有客户数据
            if (StringUtils.isBlank(errMsg)) {
                //删除临时表数据
                impData2AccntMapper.deleteTempOrder(impOrderHead);
            } else {
                //回写异常
                impOrderHead.setMessage(errMsg);
                impOrderHead.setSynStatus("Failure");
                impData2AccntMapper.tempOrderStatusUpdate(impOrderHead);
            }
        }
    }

    private Account generateAccount(ImpOrder impOrderHead, CoreUser user) {
        Account accnt = new Account();
        //客户id
        accnt.setId(keyGenerateDao.keyGenerate());
        //客户名称
        accnt.setAcctName(impOrderHead.getRecieverName());
        //客户编码
        accnt.setAcctCode(String.valueOf(accnt.getId()));
        //客户来源
        accnt.setAcctChannel(impOrderHead.getOrderSource());
        //客户阶段
        accnt.setAcctStage("OrderConsumer");
        accnt.setAcctStatus("Y");
        //客户状态
        //客户类型
        accnt.setAcctType("ChannelConsumer");
       // accnt.setAcctChannelType("Ecommerce");
        accnt.setCountry("中国");
        accnt.setProvince(impOrderHead.getProvince());
        accnt.setCity(impOrderHead.getCity());
        accnt.setDistrict(impOrderHead.getDistrict());
        //客户手机
        accnt.setMobilePhone1(impOrderHead.getRecieverPhone());
        //固话
        accnt.setAcctFixedPhone(impOrderHead.getRecieverTel());
        //添加标准字段
        accnt.setCreatedBy(user.getId());
        accnt.setLastUpdatedBy(user.getId());
        accnt.setCorpid(user.getCorpid());
        accnt.setOrgId(user.getOrgId());
        accnt.setPostnId(user.getPostnId());

        return accnt;
    }

    private AcctAddress generateAcctAddress(ImpOrder impOrder, CoreUser user, Long accntId) {
        AcctAddress addr = new AcctAddress();
        addr.setId(keyGenerateDao.keyGenerate());
        addr.setAcctId(accntId);
        addr.setCountry("中国");
        addr.setProvince(impOrder.getProvince());
        addr.setCity(impOrder.getCity());
        addr.setDistrict(impOrder.getDistrict());
        addr.setAddr(impOrder.getAddress());
        addr.setCreatedBy(user.getId());
        addr.setLastUpdatedBy(user.getId());
        addr.setCorpid(user.getCorpid());
        addr.setOrgId(user.getOrgId());
        addr.setPostnId(user.getPostnId());
        addr.setIsEffective("Y");
        addr.setAddrType("RECEIVE_ADDR");
        addr.setIsDefault("Y");
        addr.setConsignee(impOrder.getRecieverName());
        addr.setMobilePhone(impOrder.getRecieverPhone());
        return addr;
    }

    private SaleOrder generateOrder(ImpOrder impOrderHead, CoreUser user, Long accntId) {
        //订单头
        SaleOrder order = new SaleOrder();
        Long headRowId = keyGenerateDao.keyGenerate();
        order.setId(headRowId);
        order.setOrderNo(impOrderHead.getOrderCode());
        order.setOrderDate(impOrderHead.getOrderDate());
        order.setBuyerComment(impOrderHead.getBuyerComments());
        order.setSellerComment(impOrderHead.getSellerComments());
        order.setLogisticsCompany(impOrderHead.getLogisticsCompany());
        order.setLogisticsNo(impOrderHead.getLogisticsNo());
        //这里在实际取值是是取的行汇总
        order.setOrderTotalAmount(Double.parseDouble(impOrderHead.getOrderTotalAmount()));
        order.setFreight(Double.parseDouble(impOrderHead.getFreight()));
        //没有付款时间
        order.setCustomConsignee(impOrderHead.getRecieverName());
        order.setCustomMobilePhone(impOrderHead.getRecieverPhone());
        order.setProvince(impOrderHead.getProvince());
        order.setCity(impOrderHead.getCity());
        order.setDistrict(impOrderHead.getDistrict());
        order.setCustomAddr(impOrderHead.getAddress());
        order.setComments(impOrderHead.getComments());
        //订单状态-已完成，订单类型-销售订单；标准的插入方法是用了get_lov_val函数所以这里写name
        order.setStatus("已完成");
        order.setOrderType("销售订单");
        order.setOrderSource("CRM");
        order.setOrderAmount(Double.parseDouble(impOrderHead.getOrderTotalAmount()));
        //设置销售订单的销售主体字段
        order.setSalesPartyId(impOrderHead.getShopId());
        //添加消费者信息和标准字段
        order.setAcctId(accntId);
        order.setCreatedBy(user.getId());
        order.setLastUpdatedBy(user.getId());
        order.setCorpid(user.getCorpid());
        order.setOrgId(user.getOrgId());
        order.setPostnId(user.getPostnId());
        return order;
    }

    private SaleOrderItem generateOrderItem(ImpOrder impOrderItem, CoreUser user) {
        //订单行
        SaleOrderItem orderItem = new SaleOrderItem();
        orderItem.setId(keyGenerateDao.keyGenerate());
        //sku码
        orderItem.setSku(impOrderItem.getSku());
        //产品规格
        orderItem.setSpecs(impOrderItem.getProdStandard());
        //零售价
        orderItem.setProdId(impOrderItem.getProdId());
        //数量
        orderItem.setProdNum(impOrderItem.getProdNum());
        orderItem.setQty(Double.parseDouble(impOrderItem.getProdNum()));
        //优惠
        orderItem.setDiscount(Double.parseDouble(impOrderItem.getDiscount()));
        //零售价
        orderItem.setNetPrice(Double.parseDouble(impOrderItem.getActualPayment()));
        //添加标准字段
        orderItem.setCreatedBy(user.getId());
        orderItem.setLastUpdatedBy(user.getId());
        orderItem.setCorpid(user.getCorpid());
        orderItem.setOrgId(user.getOrgId());
        orderItem.setPostnId(user.getPostnId());

        return orderItem;
    }

}
